package com.nutransit.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

import com.mylibrary.mylibrary.gps.GPSTracker;
import com.mylibrary.mylibrary.parsing.AsyncTaskInterface;
import com.mylibrary.mylibrary.parsing.AsyncTaskUtility;
import com.mylibrary.mylibrary.util.CommonCode;
import com.mylibrary.mylibrary.util.SessionData;
import com.nutransit.MainActivity_Nutransit;
import com.nutransit.R;
import com.nutransit.commoncode.Webservice_parametrs;

public class MyService extends Service implements Webservice_parametrs
{
	private Timer timer;
	public static NotificationManager mNotificationManager;

	private long time_KeepAlive;
	private String user_id = null, strUserType, strReservationIds = "";
	private HashMap<String, String> hashMap;
	private  ArrayList<String> arrayList_ReservationIds;
	private double latitude, longitude;

	private CommonCode commonCode;
	private GPSTracker gpsTracker;
	private SessionData sessionData;

	@Override
	public IBinder onBind(Intent intent)
	{
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public void onCreate()
	{
		try
		{
			System.out.println("========================onCreate");
			gpsTracker = new GPSTracker(getApplicationContext());
			commonCode = new CommonCode(getApplicationContext());
			sessionData = new SessionData(getApplicationContext(), PACKAGE_NAME);
			String strUerData = sessionData.getString(TAG_data);
			strUserType = sessionData.getString(TAG_user_type);
			if (strUerData != null)
			{
				JSONObject jsonObject_data = new JSONObject(strUerData);
				if (jsonObject_data != null)
				{
					user_id = jsonObject_data.has(TAG_id) ? jsonObject_data.getString(TAG_id) : null;
				}
			}
			get_reservation_ids();
			if (user_id != null)
			{
				time_KeepAlive = 5000L;
				timer = new Timer("Testing");
				timer.schedule(updateTask, 0L, time_KeepAlive);
			}
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void onStart(Intent intent, int startId)
	{
		// For time consuming an long tasks you can launch a new thread here...
		latitude = gpsTracker.getLatitude();
		longitude = gpsTracker.getLongitude();
		System.out.println("========================onStart");
		if (commonCode.checkInternet())
		{
//			if(strUserType.equalsIgnoreCase(TAG_user))
//			{
//				
//			}
//			else
//			{
				hashMap = new HashMap<String, String>();
				hashMap.put(TAG_flag, strUserType);
				hashMap.put(TAG_id, user_id);
				hashMap.put(TAG_lat, latitude+"");
				hashMap.put(TAG_long, longitude+"");
				hashMap.put(TAG_requestid, strReservationIds+"");

				new AsyncTaskUtility(getApplicationContext(), hashMap, URL_UPDATE_LAT_LONG, false).getJSONResponse(new AsyncTaskInterface()
				{
					@Override
					public void getJSONObjectFromAsynkTask(JSONObject json)
					{
						try
						{
							if (json.getString(TAG_status).equalsIgnoreCase(SUCCESS))
							{
								if(strUserType.equalsIgnoreCase(TAG_user))
								{
									JSONArray jsonArray_data = json.getJSONArray(TAG_data);
									if(jsonArray_data.length()>0)
										get_reservation_ids();
									for (int i = 0; i < jsonArray_data.length(); i++)
									{
										JSONObject jsonObject = jsonArray_data.getJSONObject(i);
										String strFlag = jsonObject.getString(TAG_flag);
										if(!strFlag.equalsIgnoreCase("0") && arrayList_ReservationIds!=null && arrayList_ReservationIds.contains(jsonObject.getString(TAG_requestid)))
										{
											generate_notification(Integer.parseInt(jsonObject.getString(TAG_requestid)), jsonObject.getString(TAG_status));
										}
									}
								}
//								{"data":[{"requestid":"27","status":"Rejected","flag":"2"}],"message":"Location updated successfully","status":"Success"}
							}
						}
						catch (JSONException e)
						{
							e.printStackTrace();
						}
					}
				});
//			}
		}
	}

	protected void generate_notification(int mId, String strStatus)
	{
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)).setContentTitle("Request "+strStatus).setContentText("driver "+mId+" "+strStatus+" your request");
		// Creates an explicit intent for an Activity in your app
		Intent resultIntent = new Intent(this, MainActivity_Nutransit.class);
		resultIntent.putExtra(TAG_id, mId+"");
		resultIntent.putExtra(TAG_status, strStatus);
		// The stack builder object will contain an artificial back stack for the started Activity.
		// This ensures that navigating backward from the Activity leads out of your application to the Home screen.
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(MainActivity_Nutransit.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(resultPendingIntent);
		mBuilder.setAutoCancel(true);
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// mId allows you to update the notification later on.
		mNotificationManager.notify(mId, mBuilder.build());
	}

	@Override
	public void onDestroy()
	{
		timer.cancel();
		timer = null;
	}

	private TimerTask updateTask = new TimerTask()
	{
		@Override
		public void run()
		{
			startService(new Intent(getApplicationContext(), MyService.class));
		}
	};
	
	private void get_reservation_ids()
	{
		strReservationIds = sessionData.getString(TAG_reservation_ids);
		if(strReservationIds!=null)
		{
			arrayList_ReservationIds = CommonCode.convert_ArrayListString_To_Arraylist_for_string(strReservationIds);
			strReservationIds = (arrayList_ReservationIds+"").replaceAll("\\[", "").replaceAll("\\]", "");
		}
		else 
		{
			arrayList_ReservationIds = new ArrayList<String>();
			strReservationIds = "";
		}
	}

}
